<!--
 * @Author: Wangtao
 * @Date: 2020-10-13 14:33:25
 * @LastEditors: zhanwang
 * @LastEditTime: 2021-12-02 13:43:20
-->
<template>
  <div class="resize-table">
    <div class="config-table-con" ref="configTableCon">
      <u-table
        :data="data"
        :border="true"
        :max-height="tableHeight"
        :highlight-current-row="light"
        ref="Tabel"
        v-loading="showLoading"
        @select="selectChange"
        @select-all="selectAll"
        :span-method="arraySpanMethod"
        :row-key="rowKeyIdShow ? 'id' : ''"
        class="m7-table"
      >
        <template #empty> 没有查询到符合条件的记录 </template>
        <u-table-column
                type="selection"
                v-if="selection"
                fixed="left"
                width="55"
                :border-line="false"
        > </u-table-column>
        <slot name="radio"></slot>
        <slot name="column"></slot>
        <u-table-column
          align="right"
          fixed="right"
          width="40"
          :resizable="false"
        >
          <template #header>
            <el-dropdown trigger="click" @visible-change="isClick = !isClick">
              <span class="el-dropdown-link" v-show="headersConfig">
                <i class="V7_iconfont V7_iconV7tubiao_zidingyi" :class="isClick? 'icon-active': ''"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <searchCheckBox
                  :data="headers"
                  @check-change="handleCheckChange"
                ></searchCheckBox>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </u-table-column>
      </u-table>
      <div class="batch-box" v-if="isAllCheck ? pagingData.total : selectLength">
        <div class="batch-oprate">
          <el-checkbox v-model="isAllCheck" @change="checkAllData" v-if="showIsAllCheckBox">全选</el-checkbox>
          <span class="selected-count">已选择<span class="selectedNum">{{ isAllCheck ? pagingData.total : selectLength }}</span>项</span>
          <span class="selectedBtn">
              <el-button
                      type="text"
                      :disabled='item.disabled ? item.disabled : false '
                      v-for="(item, index) in batchs"
                      :key="index"
                      @click="batchClick(item)">
                {{ item.name }}
                   <el-tooltip v-if="item.tipContent" class="item" effect="dark" :content="item.tipContent" placement="top">
                    <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42"></span>
                   </el-tooltip>
              </el-button>
            </span>
          <span class="V7_iconfont V7_iconV7tubiao_guanbi oprate-close" @click="cancelSelectFun"></span>
        </div>
      </div>
    </div>
    <div class="m7-pagination config-table-pagination" v-if="showPagination">
      <el-pagination
        :class="isAllCheck?'all-check-mask':''"
        class="pages"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="pagingData.page"
        :page-sizes="[10, 20, 50]"
        :page-size="pagingData.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagingData.total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script lang="ts">
/**
 * 可改变表头宽度的table
 * 使用参数参考elementUI el-table
 * TODO 交互效果不好
 */
import { Table as UTable } from 'element-ui'
import { Component, Prop, Vue, Watch, Ref } from 'vue-property-decorator'
import { defaultPaging } from '@/components/configCommon/default-options.js'
import searchCheckBox from '@/components/configCommon/operate-modules/SearchCheckbox/index.vue'
import cloneDeep from 'lodash/cloneDeep'
@Component({
  name: 'resize-table',
  components: {
    searchCheckBox
  }
})
export default class ResizeTable extends Vue {
  @Prop({ default: () => true }) private showPagination!: boolean // 是否展示翻页，默认展示
  @Prop({ default: () => false }) private headersConfig!: boolean // 是否展示配置表头，默认不展示
  @Prop({ default: () => [] }) private headers!: any[]
  @Prop({ default: () => [] }) private data!: any[]
  @Prop({ default: () => defaultPaging }) private pagingData!: any
  @Prop({ default: () => false }) private selection!: boolean
  @Prop({ default: () => [] }) private batchs!: any[]
  @Prop({ default: () => true }) private showIsAllCheckBox!: boolean
  @Prop({ default: () => false }) private dynamic!: boolean // 是否根据动态获取的表头展示 eg: 客户模块
  @Prop({ default: () => false }) private rowKeyIdShow!: boolean
  @Prop({ default: () => true }) private light!: boolean
  @Ref() private readonly Tabel!: UTable
  private checkList: any = []
  private tableHeight: any = 0
  private isClick: boolean = false
  private isAllCheck: boolean = false

  private showLoading: any = false

  private pageSelect: any = {}

  // 选中的头部
  private checkHeaderProp: any = []
  private Datalist: any
  // 选中数据
  private selectList: any = []

  // u-tabel 下组件 初始化两次
  private checkInit = false

  private get showBatch () {
    return this.selectLength > 0 || this.isAllCheck
  }

  private get selectLength () {
    let length: any = 0
    Object.keys(this.pageSelect).forEach((page) => {
      length += this.pageSelect[page].length
    })
    return length
  }

  private mounted () {
    // 动态设置表格高度
    this.$nextTick(() => {
      this.handleSetTabelHeight()
    })
    this.handleResizeChange()
  }

  public cancelSelectFun () { // 取消选择
    this.$set(this, 'pageSelect', {}) // 清空当前选择项
    this.isAllCheck = false
    this.clearSelection() // 取消checked
  }

  private checkAllData (data) { // 选择全部
    this.isAllCheck = data
    if (data) { // 全选
      this.$set(this.pageSelect, (this.pagingData as any).page, cloneDeep(this.data)) // 存储当页数据
      this.clearSelection() // 先取消选择
      this.data.forEach(item => { // 当前页全选
        this.Tabel.toggleRowSelection([{
          row: item,
          select: true
        }]) // 当前页全选
      })
    } else { // 取消全选
      this.cancelSelectFun()
    }
  }

  public handleSetTabelHeight () {
    const con: any = this.$refs.configTableCon
    if (con) {
      const $el = con || {}
      const conStyles = (window as any).getComputedStyle($el)
      const tableH = parseInt(conStyles.height, 10)
      if (this.selectLength > 0) {
        this.tableHeight = tableH - 12 - 50
      } else if (!this.showPagination) { // 没有翻页
        this.tableHeight = tableH + 26
      } else {
        this.tableHeight = tableH - 12
      }
    }
  }

  private handleResizeChange () {
    (window as any).addEventListener('resize', () => {
      this.handleSetTabelHeight()
    })
  }

  private handleCurrentChange (page) {
    this.$emit('pageChange', page)
  }

  private handleSizeChange (size) {
    this.$emit('pageSizeChange', size)
  }

  private handleCheckChange (Datalist, isInit) {
    if (this.checkInit && isInit === true && !this.dynamic) { // 是否是初始化 && 不是初始化用动态设置的表头
      return
    }
    this.showLoading = true
    setTimeout(() => {
      this.showLoading = false
    }, 400)
    if (isInit === true) {
      this.checkInit = true
    }
    this.$set(this, 'checkList', Datalist)
    this.$emit('checkHeadersChange', Datalist, isInit)
  }

  get getHeadersShowLength () {
    let length = 0
    this.checkList.forEach((item) => {
      if (item.show) {
        length++
      }
    })
    return length
  }

  private arraySpanMethod ({ row, column, rowIndex, columnIndex }) {
    let oprateIndex
    if (this.selection) {
      oprateIndex = this.getHeadersShowLength
    } else {
      oprateIndex = this.getHeadersShowLength - 1
    }
    if (columnIndex === oprateIndex) {
      return [1, 2]
    }
  }

  private selectChange (selection, row) { // 单独选择某一个
    this.isAllCheck = false
    if (selection && selection.length === this.pagingData.total) {
      this.isAllCheck = true
    }
    this.$set(this.pageSelect, (this.pagingData as any).page, cloneDeep(selection))
    this.handleSetTabelHeight()
  }

  private selectAll (selection) { // 单页全选
    if (selection && selection.length === this.pagingData.total && this.showIsAllCheckBox) {
      this.isAllCheck = true
    }
    if (selection) {
      this.$set(this.pageSelect, (this.pagingData as any).page, cloneDeep(selection))
      if (selection.length <= 0) {
        this.isAllCheck = false
      }
    } else {
      this.$set(this.pageSelect, (this.pagingData as any).page, [])
      this.isAllCheck = false
    }
  }

  public clearSelection () {
    this.Tabel.clearSelection()
  }

  private mergeArray (arr1, arr2) {
    const Arr: any = []
    for (let i = 0; i < arr1.length; i++) {
      Arr.push(arr1[i])
    }
    let Dup
    for (let i = 0; i < arr2.length; i++) {
      Dup = false
      for (let k = 0; k < arr1.length; k++) {
        if (arr2[i] === arr1[k]) {
          Dup = true
          break
        }
      }
      if (!Dup) {
        Arr.push(arr2[i])
      }
    }
    return Arr
  }

  private batchClick (item) {
    const selectList: string[] = []
    Object.keys(this.pageSelect).forEach((page) => {
      if (this.pageSelect[page].length > 0) {
        this.pageSelect[page].forEach((pageItem) => {
          selectList.push(pageItem._id)
        })
      }
    })
    this.$emit('batchClick', item.action, this.showIsAllCheckBox ? (this.isAllCheck || selectList) : selectList)
  }

  @Watch('showBatch')
  private selectionChange () {
    this.handleSetTabelHeight() // 批量操作条消失，高度要重新计算
  }

  @Watch('data')
  private dataChange (list) {
    this.$nextTick(() => {
      this.Tabel.clearSelection()
      const rows = cloneDeep(this.pageSelect[(this.pagingData as any).page]);
      if (rows && rows.length > 0) {
        rows.forEach(row => {
          list.forEach((lItem, index) => {
            if (lItem._id === row._id) {
              this.Tabel.toggleRowSelection([{
                row: list[index],
                select: true
              }])
            }
          })
        })
      }
    })
  }
}
</script>

<style lang="stylus" scoped>
.resize-table
  display flex
  flex-direction column
  justify-content space-between
  height 100%
  font-size 12px
  width 100%
  /deep/ .el-table__column-resize-proxy
          border-left: 2px dashed $c-main !important
  /deep/ .el-table--border
          border: none
  /deep/ .el-table--border td
          border-right: 3px solid transparent
  /deep/ .el-table-column--selection
          padding-left: 4px
  /deep/ .el-table--border td:last-child
          border-right: 1px solid #EBEEF5
  /deep/ .el-table--border th
            border-right: 3px solid transparent
  /deep/ .el-table--border th:last-child
          border-right: none !important
  /deep/ .el-table--border th:not(.el-table-column--selection):not(.is-right)::after
            content: ''
            position: absolute
            right 0
            top 25%
            height 50%
            opacity: 0
            width 3px
            background $c-main
            border-radius: 2px
  /deep/ .el-table--border th:not(.el-table-column--selection):not(.is-right):hover::after
          opacity: 1
  .config-table-con
    height calc(100% - 50px)
    overflow auto
    box-sizing border-box
    padding-top 10px
    display flex
    flex-direction column
    justify-content space-between
  .config-table-pagination
    box-sizing border-box
    display flex
    justify-content flex-end
    height 50px
    align-items center
  .V7_iconfont
    font-size 12px
  .V7_iconV7tubiao_zidingyi
    color $icon-gray
    cursor pointer
  .icon-active
    color $c-main
  >>> .el-table .caret-wrapper
    height 20px
    .ascending
      top -1px
    .descending
      bottom -1px
  .batch-box
    height 50px
    display flex
    flex-direction column
    justify-content flex-end
    .batch-oprate
      height 40px
      line-height 40px
      background #E5F3FD
      border-radius 4px
      display flex
      align-items center
      padding 0 16px 0
      box-sizing border-box
      position relative
      .selected-count
         padding-left 20px
      .oprate-close
        color $icon-gray
        font-size 14px
        cursor pointer
        position absolute
        right 16px
        &:hover
          color $c-main
    .selectedNum
      color $c-main
      margin 0 5px 0
    .selectedBtn
      margin-left 20px
    .line
      height 9px
      display inline-block
      width 1px
      background $c-main
      margin 0px 5px 0
      opacity 0.3
  .pages
    box-sizing border-box
    display flex
    justify-content flex-end
    height 50px
    align-items center
    position relative
  .all-check-mask:after
    content ''
    position absolute
    bottom 0
    left 0
    width 100%
    height 100%
    background hsla(0,0%,100%,.3)
    z-index 100
    cursor not-allowed
</style>
